import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import { AgentDto, AgentStatus, AgentType, GetAgentListInput } from '@services/agentService';
import agentService from '@services/agentService';

// 状态接口定义
interface AgentState {
  agents: AgentDto[];
  loading: boolean;
  error: string | null;
  totalCount: number;
  filters: GetAgentListInput;
  selectedAgent: AgentDto | null;
  stats: any;
}

// 动作类型定义
type AgentAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_AGENTS'; payload: { agents: AgentDto[]; totalCount: number } }
  | { type: 'SET_FILTERS'; payload: GetAgentListInput }
  | { type: 'SET_SELECTED_AGENT'; payload: AgentDto | null }
  | { type: 'SET_STATS'; payload: any }
  | { type: 'ADD_AGENT'; payload: AgentDto }
  | { type: 'UPDATE_AGENT'; payload: AgentDto }
  | { type: 'DELETE_AGENT'; payload: string }
  | { type: 'RESET_FILTERS' };

// 初始状态
const initialState: AgentState = {
  agents: [],
  loading: false,
  error: null,
  totalCount: 0,
  filters: {
    skipCount: 0,
    maxResultCount: 10,
    sorting: 'creationtimedesc'
  },
  selectedAgent: null,
  stats: null
};

// Reducer函数
function agentReducer(state: AgentState, action: AgentAction): AgentState {
  switch (action.type) {
    case 'SET_LOADING':
      return { ...state, loading: action.payload, error: null };
    
    case 'SET_ERROR':
      return { ...state, loading: false, error: action.payload };
    
    case 'SET_AGENTS':
      return {
        ...state,
        loading: false,
        agents: action.payload.agents,
        totalCount: action.payload.totalCount,
        error: null
      };
    
    case 'SET_FILTERS':
      return { ...state, filters: { ...state.filters, ...action.payload } };
    
    case 'SET_SELECTED_AGENT':
      return { ...state, selectedAgent: action.payload };
    
    case 'SET_STATS':
      return { ...state, stats: action.payload };
    
    case 'ADD_AGENT':
      return {
        ...state,
        agents: [action.payload, ...state.agents],
        totalCount: state.totalCount + 1
      };
    
    case 'UPDATE_AGENT':
      return {
        ...state,
        agents: state.agents.map(agent =>
          agent.id === action.payload.id ? action.payload : agent
        ),
        selectedAgent: state.selectedAgent?.id === action.payload.id 
          ? action.payload 
          : state.selectedAgent
      };
    
    case 'DELETE_AGENT':
      return {
        ...state,
        agents: state.agents.filter(agent => agent.id !== action.payload),
        totalCount: state.totalCount - 1,
        selectedAgent: state.selectedAgent?.id === action.payload ? null : state.selectedAgent
      };
    
    case 'RESET_FILTERS':
      return {
        ...state,
        filters: {
          skipCount: 0,
          maxResultCount: 10,
          sorting: 'creationtimedesc'
        }
      };
    
    default:
      return state;
  }
}

// Context创建
const AgentContext = createContext<{
  state: AgentState;
  dispatch: React.Dispatch<AgentAction>;
  actions: AgentActions;
} | null>(null);

// 动作定义接口
interface AgentActions {
  fetchAgents: (filters?: GetAgentListInput) => Promise<void>;
  fetchAgentById: (id: string) => Promise<void>;
  createAgent: (data: any) => Promise<void>;
  updateAgent: (id: string, data: any) => Promise<void>;
  deleteAgent: (id: string) => Promise<void>;
  updateAgentStatus: (id: string, status: AgentStatus) => Promise<void>;
  activateAgent: (id: string) => Promise<void>;
  deactivateAgent: (id: string) => Promise<void>;
  resetAgentStats: (id: string) => Promise<void>;
  fetchAgentStats: (id: string) => Promise<void>;
  batchUpdateAgentStatus: (agentIds: string[], status: AgentStatus) => Promise<void>;
  batchDeleteAgents: (agentIds: string[]) => Promise<void>;
  setFilters: (filters: Partial<GetAgentListInput>) => void;
  resetFilters: () => void;
  setSelectedAgent: (agent: AgentDto | null) => void;
  getSimpleAgents: (isActive?: boolean) => Promise<any[]>;
}

// Provider组件
interface AgentProviderProps {
  children: ReactNode;
}

export function AgentProvider({ children }: AgentProviderProps) {
  const [state, dispatch] = useReducer(agentReducer, initialState);

  // 创建动作函数
  const actions: AgentActions = {
    // 获取智能体列表
    fetchAgents: async (filters?: GetAgentListInput) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        
        const finalFilters = { ...state.filters, ...filters };
        const response = await agentService.getAgents(finalFilters);
        
        dispatch({
          type: 'SET_AGENTS',
          payload: {
            agents: response.items || [],
            totalCount: response.totalCount || 0
          }
        });
        
        dispatch({ type: 'SET_FILTERS', payload: finalFilters });
      } catch (error) {
        console.error('获取智能体列表失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '获取智能体列表失败' });
      }
    },

    // 根据ID获取智能体详情
    fetchAgentById: async (id: string) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        const agent = await agentService.getAgent(id);
        dispatch({ type: 'SET_SELECTED_AGENT', payload: agent });
      } catch (error) {
        console.error('获取智能体详情失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '获取智能体详情失败' });
      }
    },

    // 创建智能体
    createAgent: async (data: any) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        const agent = await agentService.createAgent(data);
        dispatch({ type: 'ADD_AGENT', payload: agent });
      } catch (error) {
        console.error('创建智能体失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '创建智能体失败' });
        throw error;
      }
    },

    // 更新智能体
    updateAgent: async (id: string, data: any) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        const agent = await agentService.updateAgent(id, data);
        dispatch({ type: 'UPDATE_AGENT', payload: agent });
      } catch (error) {
        console.error('更新智能体失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '更新智能体失败' });
        throw error;
      }
    },

    // 删除智能体
    deleteAgent: async (id: string) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        await agentService.deleteAgent(id);
        dispatch({ type: 'DELETE_AGENT', payload: id });
      } catch (error) {
        console.error('删除智能体失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '删除智能体失败' });
        throw error;
      }
    },

    // 更新智能体状态
    updateAgentStatus: async (id: string, status: AgentStatus) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        await agentService.updateAgentStatus(id, status);
        // 重新获取智能体列表以更新状态
        await actions.fetchAgents();
      } catch (error) {
        console.error('更新智能体状态失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '更新智能体状态失败' });
        throw error;
      }
    },

    // 激活智能体
    activateAgent: async (id: string) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        await agentService.activateAgent(id);
        await actions.fetchAgents();
      } catch (error) {
        console.error('激活智能体失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '激活智能体失败' });
        throw error;
      }
    },

    // 停用智能体
    deactivateAgent: async (id: string) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        await agentService.deactivateAgent(id);
        await actions.fetchAgents();
      } catch (error) {
        console.error('停用智能体失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '停用智能体失败' });
        throw error;
      }
    },

    // 重置智能体统计信息
    resetAgentStats: async (id: string) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        await agentService.resetAgentStats(id);
        await actions.fetchAgents();
      } catch (error) {
        console.error('重置智能体统计信息失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '重置智能体统计信息失败' });
        throw error;
      }
    },

    // 获取智能体统计信息
    fetchAgentStats: async (id: string) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        const stats = await agentService.getAgentStats(id);
        dispatch({ type: 'SET_STATS', payload: stats });
      } catch (error) {
        console.error('获取智能体统计信息失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '获取智能体统计信息失败' });
      }
    },

    // 批量更新智能体状态
    batchUpdateAgentStatus: async (agentIds: string[], status: AgentStatus) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        await agentService.batchUpdateAgentStatus({ agentIds, status });
        await actions.fetchAgents();
      } catch (error) {
        console.error('批量更新智能体状态失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '批量更新智能体状态失败' });
        throw error;
      }
    },

    // 批量删除智能体
    batchDeleteAgents: async (agentIds: string[]) => {
      try {
        dispatch({ type: 'SET_LOADING', payload: true });
        await agentService.batchDeleteAgents({ agentIds });
        await actions.fetchAgents();
      } catch (error) {
        console.error('批量删除智能体失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '批量删除智能体失败' });
        throw error;
      }
    },

    // 设置过滤器
    setFilters: (filters: Partial<GetAgentListInput>) => {
      dispatch({ type: 'SET_FILTERS', payload: filters });
    },

    // 重置过滤器
    resetFilters: () => {
      dispatch({ type: 'RESET_FILTERS' });
    },

    // 设置选中的智能体
    setSelectedAgent: (agent: AgentDto | null) => {
      dispatch({ type: 'SET_SELECTED_AGENT', payload: agent });
    },

    // 获取智能体简要列表
    getSimpleAgents: async (isActive: boolean = true) => {
      try {
        return await agentService.getSimpleAgents(isActive);
      } catch (error) {
        console.error('获取智能体简要列表失败:', error);
        return [];
      }
    }
  };

  // 初始化时获取智能体列表
  useEffect(() => {
    actions.fetchAgents();
  }, []);

  return (
    <AgentContext.Provider value={{ state, dispatch, actions }}>
      {children}
    </AgentContext.Provider>
  );
}

// Hook函数
export function useAgent() {
  const context = useContext(AgentContext);
  if (!context) {
    throw new Error('useAgent must be used within an AgentProvider');
  }
  return context;
}

// 选择器Hook
export function useAgents() {
  const { state } = useAgent();
  return state.agents;
}

export function useAgentLoading() {
  const { state } = useAgent();
  return state.loading;
}

export function useAgentError() {
  const { state } = useAgent();
  return state.error;
}

export function useAgentFilters() {
  const { state, actions } = useAgent();
  return {
    filters: state.filters,
    setFilters: actions.setFilters,
    resetFilters: actions.resetFilters
  };
}

export function useSelectedAgent() {
  const { state, actions } = useAgent();
  return {
    selectedAgent: state.selectedAgent,
    setSelectedAgent: actions.setSelectedAgent,
    fetchAgentById: actions.fetchAgentById
  };
}